<template>
  <el-dialog title="添加入库单" :visible.sync="StorageReceiptDialog" @close="handleClose" width="80%" class="dialog">
    <template slot="title">
      <span style="color: rgba(52, 69, 99, 1); font-size: 18px;font-weight: bold; margin-left: 5px;margin-top: 34px;">
        添加入库单
      </span>
      <br /><br />
      <hr />
    </template>
    <div class="dialog-content">
      <el-form class="addForm">
        <el-form-item label="入库单编号：" label-width="120px">
          <el-input style="width: 40%;" v-model="input"></el-input>
        </el-form-item>
        <el-form-item label="入库商品" label-width="90px">
          <el-link style="float:right;" type="primary" @click="addProduct" :underline="false">+商品</el-link>
        </el-form-item>
        <div v-for="(tag, index) in tags" :key="tag.commodityName" class="productTable">
          <el-tag closable @close="() => deleteProduct(index)">
            {{ tag.commodityName }}
          </el-tag>
          <el-table :data="[tag.details]" border style="width: 100%;">
            <el-table-column v-for="(label, key) in tableColumns" :key="key" :prop="key" :label="label"
              min-width="100"></el-table-column>
            <el-table-column label="单位" min-width="100">
              {{ tag.commodityUnit }}
            </el-table-column>
            <el-table-column label="单价" min-width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price">
                  <template #prefix>￥</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="数量" min-width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.number"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="金额" min-width="100">
                ￥{{ tag.details.price * tag.details.number }}
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <AddProduct :dialogVisible.sync="visible" @updateTags="updateTags"></AddProduct>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="info" @click="StorageReceiptDialog = false" class="footer-button">
        取消
      </el-button>
      <el-button @click="submitInBoundOrder()" class="footer-button confirm-button">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import AddProduct from '@/components/AddProduct.vue';
import { addStock } from '@/api/api.js';

export default {
  components: {
    AddProduct
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
  },
  computed: {
    tableColumns() {
      if (this.tags.length > 0 && this.tags[0].details) {
        console.log(this.tags)
        console.log(this.tags.length)
        console.log(this.tags[0].details)
        // 只生成固定的列，不包含 unit、price、number 和 money
        const keysToExclude = ['unit', 'price', 'number', 'money'];
        // Object.keys(this.tags[0].details)：获取第一个商品的 details 属性的所有键（即列名）。
        // reduce((columns, key) => {...}, {})：遍历所有列名并生成一个包含这些列名的对象 columns。
        return Object.keys(this.tags[0].details).reduce((columns, key) => {
          //columns[key] = key：将每个键（列名）添加到 columns 对象中，键和值都为列名。
          if (!keysToExclude.includes(key)) {
            columns[key] = key; 
          }
          console.log(typeof columns)
          return columns;
        }, {});
      }
      return {};
    }
  },
  data() {
    return {
      StorageReceiptDialog: this.dialogVisible,
      visible: false,
      input: '',
      tags: [],
    };
  },
  methods: {
    handleClose() {
      this.$emit('update:dialogVisible', false);
      this.tags = [];
      this.input = "";
    },
    deleteProduct(index) {
      this.tags.splice(index, 1);
    },
    addProduct() {
      this.visible = true;
    },
    updateTags(newTags) {
      this.tags = newTags;
      console.log(newTags)
      console.log("父组件的tgas", this.tags)
    },
    async submitInBoundOrder() {
      // 获取入库单编号
      const receiptNumber = this.input;

      console.log("this.tags 内容:", JSON.stringify(this.tags, null, 2));

      // 构建包含多个商品的数组
      const formDataList = this.tags.map(tag => ({
        addSkuDTOList: [{
          money: tag.details.price * tag.details.number,
          price: tag.details.price,
          skuCode: tag.skucode,
          stockNumber: tag.details.number,
          unit: tag.commodityUnit
        }],
        commodityId: tag.id,
        remark: "",
        shopId: sessionStorage.getItem('shopid'),  // 商铺id
        stockSn: receiptNumber
      }));

      console.log("提交表单数据:", JSON.stringify(formDataList, null, 2));

      // 提交整个数组
      try {
        const response = await addStock(formDataList);
        console.log("提交成功:", response);
        if (response.data.code == 200) {
          this.$message({
            type: 'success',
            message: response.data.result
          });
          this.handleClose();
          // 发出 reloadData 事件
          this.$emit('reloadData');
        }
      } catch (error) {
        console.error("提交失败:", error);
      }
    }



  },
  watch: {
    dialogVisible(newVal) {
      this.StorageReceiptDialog = newVal;
    }
  }
};
</script>

<style scoped>
.dialog {
  max-height: 100vh !important;
  overflow-y: hidden;
  left: 15%;
}

.dialog-content {
  max-height: calc(100vh - 200px);
  overflow-y: auto;
  height: 480px;
}


.el-icon-search {
  margin-top: 14px;
  width: 15px;
  margin-left: 6px;
}

.el-pagination {
  float: right;
}

.dialog-footer {
  position: absolute;
  bottom: 10px;
  right: 0;
  width: 100%;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  padding: 10px 20px;
  border-top: 1px solid #ebeef5;
}

.footer-button {
  font-size: 14px;
  height: 38px;
  width: 150px;
  margin-right: 8px;
}

.confirm-button {
  background-color: rgba(90, 52, 179, 1);
  color: white;
}

.productTable {
  margin-top: 10px;
}

.el-table .el-table--fit .el-table--border .el-table--enable-row-hover {
  background-color: #ebeef5;

}
</style>
